package com.aaa.security;

import com.aaa.dao.UserDetaConfigDao;
import com.aaa.entity.ResultCode;
import com.aaa.entity.SecurityUser;
import com.aaa.entity.TUserDetails;
import com.aaa.service.FuserServiceDao;
import com.aaa.service.UserServiceDao;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public class UserDetailsConfig implements UserDetailsService {
    //前台登录
    @Resource
    FuserServiceDao fuserServiceDao;
    //后台登录
    @Resource
    UserServiceDao userServiceDao;
//    UserDetaConfigDao userDetaConfigDao;

    @Resource
    HttpServletRequest request;
    /**
     * 根据用户名获取用户信息
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("用户名"+s);
        //获取是哪一个客户端
        String client_id = request.getParameter("client_id");
        SecurityUser securityUser=null;
        if (client_id.equals("aaa")){//说明是后台登录
            System.out.println("后台登录");
            securityUser = userServiceDao.loadUserByUsername(s);
            System.out.println(securityUser);
        }else if (client_id.equals("bbb")){//说明是前台登录
            System.out.println("前台登录");
            securityUser = fuserServiceDao.loadUserByUsername(s);
            System.out.println(securityUser);
        }
        if (null!=securityUser){
            if (securityUser.isEnabled()){
               return securityUser;
            }else {
                throw new DisabledException(ResultCode.NO_DISABLED.getMsg());
            }
        }else {
            throw new UsernameNotFoundException("用户不存在");
        }
        //根据用户名查询
//        List<TUserDetails>  tUserDetails = userDetaConfigDao.finduname(s);
//        System.out.println(tUserDetails);
//        if (tUserDetails.size()==1){
//         return tUserDetails.get(0);
//        }else {
//            return (UserDetails) new UsernameNotFoundException("没有查询到该登录用户");
//        }

    }
}
